package com.kexio.email.config;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import com.kexio.email.impl.EmailServiceImpl;
import com.kexio.email.service.EmailService;

/**
 * 邮件服务自动配置
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Configuration
@ConditionalOnProperty(prefix = "kexio.email", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(EmailProperties.class)
@ComponentScan(basePackages = "com.kexio.email")
public class EmailAutoConfiguration {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailAutoConfiguration.class);
    
    /**
     * JavaMailSender Bean
     * 根据配置文件创建邮件发送器
     */
    @Bean
    @ConditionalOnMissingBean
    public JavaMailSender javaMailSender(EmailProperties properties) {
        logger.info("创建 JavaMailSender");
        
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        
        // 基本配置
        EmailProperties.SmtpConfig smtp = properties.getSmtp();
        mailSender.setHost(smtp.getHost());
        mailSender.setPort(smtp.getPort());
        mailSender.setUsername(smtp.getUsername());
        mailSender.setPassword(smtp.getPassword());
        
        // 设置默认编码
        mailSender.setDefaultEncoding("UTF-8");
        
        // JavaMail 属性配置
        Properties javaMailProperties = new Properties();
        javaMailProperties.put("mail.smtp.auth", smtp.isAuth());
        javaMailProperties.put("mail.smtp.starttls.enable", smtp.isStarttlsEnable());
        javaMailProperties.put("mail.smtp.starttls.required", smtp.isStarttlsEnable());
        javaMailProperties.put("mail.smtp.ssl.enable", smtp.isSslEnable());
        javaMailProperties.put("mail.smtp.connectiontimeout", smtp.getConnectionTimeout());
        javaMailProperties.put("mail.smtp.timeout", smtp.getTimeout());
        javaMailProperties.put("mail.smtp.writetimeout", smtp.getWriteTimeout());
        
        // QQ邮箱特殊配置
        if (smtp.getHost().contains("qq.com")) {
            javaMailProperties.put("mail.smtp.ssl.trust", smtp.getHost());
            javaMailProperties.put("mail.smtp.ssl.protocols", "TLSv1.2");
        }
        
        mailSender.setJavaMailProperties(javaMailProperties);
        
        logger.info("JavaMailSender 创建成功: {}:{}", smtp.getHost(), smtp.getPort());
        return mailSender;
    }
    
    /**
     * 邮件服务Bean
     */
    @Bean
    @ConditionalOnMissingBean
    public EmailService emailService() {
        logger.info("注册邮件服务: EmailServiceImpl");
        return new EmailServiceImpl();
    }
    
    /**
     * 邮件服务启动日志
     */
    @Bean
    public EmailStartupLogger emailStartupLogger(EmailProperties properties) {
        return new EmailStartupLogger(properties);
    }
    
    /**
     * 启动日志组件
     */
    public static class EmailStartupLogger {
        
        private final EmailProperties properties;
        
        public EmailStartupLogger(EmailProperties properties) {
            this.properties = properties;
            logStartupInfo();
        }
        
        private void logStartupInfo() {
            logger.info("========================================");
            logger.info("📧 Kexio Email Service 启动成功!");
            logger.info("🔧 SMTP配置:");
            logger.info("   服务器: {}:{}", properties.getSmtp().getHost(), properties.getSmtp().getPort());
            logger.info("   用户名: {}", maskEmail(properties.getSmtp().getUsername()));
            logger.info("   认证: {}", properties.getSmtp().isAuth() ? "✅ 启用" : "❌ 禁用");
            logger.info("   TLS: {}", properties.getSmtp().isStarttlsEnable() ? "✅ 启用" : "❌ 禁用");
            logger.info("   SSL: {}", properties.getSmtp().isSslEnable() ? "✅ 启用" : "❌ 禁用");
            
            logger.info("👤 发件人配置:");
            logger.info("   默认邮箱: {}", maskEmail(properties.getSender().getDefaultFromEmail()));
            logger.info("   默认名称: {}", properties.getSender().getDefaultFromName());
            
            logger.info("⚡ 异步配置:");
            logger.info("   异步发送: {}", properties.getAsync().isEnabled() ? "✅ 启用" : "❌ 禁用");
            if (properties.getAsync().isEnabled()) {
                logger.info("   核心线程数: {}", properties.getAsync().getCorePoolSize());
                logger.info("   最大线程数: {}", properties.getAsync().getMaxPoolSize());
                logger.info("   队列容量: {}", properties.getAsync().getQueueCapacity());
            }
            
            logger.info("🔄 重试配置:");
            logger.info("   最大重试次数: {}", properties.getRetry().getMaxRetryCount());
            logger.info("   重试间隔: {}秒", properties.getRetry().getRetryIntervalSeconds());
            logger.info("   指数退避: {}", properties.getRetry().isExponentialBackoff() ? "✅ 启用" : "❌ 禁用");
            
            logger.info("📎 限制配置:");
            logger.info("   最大附件大小: {}MB", properties.getLimit().getMaxAttachmentSizeMb());
            logger.info("   最大附件数量: {}个", properties.getLimit().getMaxAttachmentCount());
            logger.info("   每小时限制: {}封", properties.getLimit().getMaxSendPerHour());
            logger.info("   每日限制: {}封", properties.getLimit().getMaxSendPerDay());
            
            logger.info("📊 记录配置:");
            logger.info("   发送记录: {}", properties.getRecord().isEnabled() ? "✅ 启用" : "❌ 禁用");
            logger.info("   保留天数: {}天", properties.getRecord().getRetentionDays());
            logger.info("   保存内容: {}", properties.getRecord().isSaveContent() ? "✅ 启用" : "❌ 禁用");
            logger.info("   自动清理: {}", properties.getRecord().isAutoCleanup() ? "✅ 启用" : "❌ 禁用");
            
            logger.info("🎨 模板配置:");
            logger.info("   默认引擎: {}", properties.getTemplate().getDefaultEngine());
            logger.info("   模板缓存: {}", properties.getTemplate().isEnableCache() ? "✅ 启用" : "❌ 禁用");
            logger.info("   模板路径: {}", properties.getTemplate().getPathPrefix());
            
            logger.info("🚀 邮件服务已就绪!");
            logger.info("========================================");
        }
        
        /**
         * 掩码邮箱地址
         */
        private String maskEmail(String email) {
            if (email == null || email.trim().isEmpty()) {
                return "未配置";
            }
            int atIndex = email.indexOf('@');
            if (atIndex > 0) {
                String username = email.substring(0, atIndex);
                String domain = email.substring(atIndex);
                if (username.length() > 2) {
                    return username.substring(0, 2) + "***" + domain;
                }
            }
            return email;
        }
    }
}
